<template>
  <div class="management-user views-container">
    <el-dialog :visible.sync="dialogVisibleImg" width="40%" custom-class="reset-pwd wlm-form-dialog dialog-table">
      <div class="hidemask flex-row flex-justify-c flex-align-c" v-if="showMask">
        <el-progress type="circle" :percentage="$percentage"></el-progress>
      </div>
      <div class="wlm-form">
        <div class="wlm-form-header wlm-dialog-fixheader">
          <span class="wlm-dialog-inlenr">用户合并</span>
        </div>
        <div style="margin:20px">
          <div class="yellowBox">
            <p>系统通过手机号或统一用户unionid来判断用户唯一性，来合并重复的用户信息。</p>
            <p>注：</p>
            <p>1.unionid为微信开放平台标志，同一开放平台下的小程序和公众号用户的unionid一样。</p>
            <p>2.在使用unionid方式合并用户数据之前，请先点击本页面“同步微信用户”按钮同步用户的unionid（未关注的用户无法获取）。</p>
            <p>3.正常情况下此合并操作只需执行一次，因为本功能上线之后，用户微信登录时会自动获取unionid然后自动判断合并。</p>
          </div>
          <div class="flex-row backBox">
            <div class="backBoxItem">
              <p>总用户数</p>
              <p class="num">{{getUserMergeData.total_num}}</p>
            </div>
            <div class="backBoxItem B">
              <p>手机号重复数量</p>
              <p class="num">{{getUserMergeData.mobileRepeatNum}}</p>
            </div>
            <div class="backBoxItem C">
              <p>手机号为空数</p>
              <p class="num">{{getUserMergeData.mobileEmptyNum}}</p>
            </div>
            <div class="backBoxItem C">
              <p>重复unionid数</p>
              <p class="num">{{getUserMergeData.unionidRepeatNum}}</p>
            </div>
            <div class="backBoxItem">
              <p>unionid为空数</p>
              <p class="num">{{getUserMergeData.unionidEmptyNum}}</p>
            </div>
          </div>
          <div class="flex-row flex-justify-c">
            <el-button type="primary" @click="setUserMerge">开始合并用户</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <export-file-in ref="exportFileIn" :config="{title:'导入用户信息', desinfo:'请先导出用户数据, 填好信息, 再导入文件即可。',api: exportFileInApi}" :changeEvt="filesSerch">
     <el-button slot="export" size="mini" :data-query="JSON.stringify(tableFormatData.userTable.files)" v-if="isIndependent"  type="text" v-exceldown="{path:'web/doc/用户模版.csv', isBase: false}">下载用户模板</el-button>
      <el-button slot="export" size="mini" :data-query="JSON.stringify(tableFormatData.userTable.files)" v-if="!isIndependent" type="text" v-exceldown="{path:'addons/weliam_areashop/web/doc/用户模版.csv', isBase: false}">下载用户模板</el-button>
       <!-- <el-button plain icon="document" :data-query="JSON.stringify(tableFormatData.userTable.files)" v-exceldown="{path:'outputMember&',query: {}}">{{$t('excel.export') }}会员</el-button> -->
    </export-file-in>
    <div class="wlm-table">
      <div class="wlm-table-header">
        <el-form :model="tableFormatData.userTable.files" size="small" label-width="85px" class="retail-form" label-position="right">
          <el-form-item label class="filter">
            <el-form-item label="用户：" class="search">
              <el-input @keyup.enter.native="filesSerch" v-model="tableFormatData.userTable.files.keyword" placeholder="请输入昵称或手机号" style="width:160px;"></el-input>
            </el-form-item>
            <el-form-item label="黑名单：" class="filter">
              <el-select v-model="tableFormatData.userTable.files.status" placeholder="请选择">
                <el-option v-for="item in [{lable:'全部',value:'0'},{lable:'是',value:'3'},{lable:'否',value:'1'}]" :key="item.value" :label="item.lable" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label class="filter">
            <el-form-item label="注册来源：">
              <el-select v-model="tableFormatData.userTable.files.source" placeholder="请选择">
                <el-option :key="2" label="微信小程序" :value="2" v-if="patSetting.channel.wxapp.open"></el-option>
                <el-option :key="3" label="H5" :value="3" v-if="patSetting.channel.H5.open"></el-option>
                <el-option :key="4" label="微信公众号" :value="4" v-if="patSetting.channel.wechat.open"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="注册时间：">
              <el-date-picker v-model="tableFormatData.userTable.files.time" value-format="timestamp" :default-time="['00:00:00', '23:59:59']" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="备注：" class="remark">
              <el-input  v-model="tableFormatData.userTable.files.remarks"  type="text" placeholder="请输入备注" ></el-input>
            </el-form-item>
          </el-form-item>
          <el-form-item label class="filter-btns">
            <div class="flex-row flex-justify-b flex-align-c" style="width:100%;">
              <div>
                <el-button type="primary" @click="filesSerch">筛选</el-button>
                <el-button plain @click="$refs.exportFileIn.toggle()">用户导入</el-button>
                <el-button type="text" @click="filesbtn">清空筛选条件</el-button>
              </div>
              <div class="flex-row flex-justify-e flex-align-c">
                <el-progress v-if="tableFormatData.userTable.pagination.is_syn" type="circle" :percentage="Number(ProgressBar)" class="ProgressBar" :width="45" :height="45"></el-progress>
                  <div>
                      <el-popover placement="top-start" class="Tips" title="提示" width="250" trigger="hover" content="建议在夜深人静无人访问的时间段同步，以免影响正常业务。">
                      <el-button plain @click="mergeUser(btn)" slot="reference" :loading="tableFormatData.userTable.pagination.is_syn">同步微信用户</el-button>
                    </el-popover>
                    <el-popover
                      placement="top-start"
                      :style="{'z-index':tableFormatData.userTable.pagination.is_syn?50:10}"
                                          class="Tipsbtn"
                      title="提示"
                      width="250"
                      trigger="hover"
                    content="如出现意外，请重新点击按钮重新同步！">
                      <el-button plain slot="reference" :style="{'width':tableFormatData.userTable.pagination.is_syn?'135px':'116px'}" @click="synchronization">重启同步用户</el-button>
                    </el-popover>
                  </div>

                <el-button plain @click="getUserMerge" class="Height">合并用户数据</el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="wlm-table-content">
        <el-table :ref="tableFormatData.userTable.key"  style="width: 100%" :data="tableFormatData.userTable.tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="date" label="uid" width="75">
            <template slot-scope="scope">
              <span>{{scope.row.user_id}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="用户">
            <template slot-scope="scope">
              <div class="flex-row">
                <img width="50" height="50" :src="scope.row.avatarUrl || $store.getters.usersAvatar" style="margin-right:10px;" />
                <div class="text-left">
                  <p>{{scope.row.nickName || '-'}}</p>
                  <!-- <p>{{`ID：${scope.row.user_id}` || '-'}}</p> -->
                  
                  <!-- <el-tooltip class="item" effect="dark" :content="sourceType[`${scope.row.source}`]" placement="top">
                    <img height="20" width="20" :src="sourceImg[`${scope.row.source || '-'}`]" alt />
                  </el-tooltip> wechat_openid-->
                  <!-- <div v-if="scope.row.open_id!=0 && scope.row.open_id!=''&&scope.row.open_id!='null' && scope.row.open_id!='undefined'"> -->
                   
                     <el-tooltip class="item" effect="dark" :content="sourceType[`${2}`]" placement="top" v-if="scope.row.open_id!=0 && scope.row.open_id!=''&&scope.row.open_id!=null && scope.row.open_id!=undefined">
                        <img height="20" width="20" :src="sourceImg[`${2}`]" alt />
                      </el-tooltip>
                  <!-- {{JSON.parse(scope.row.toutiao_openid)!=['0']}} -->
                     <!-- <el-tooltip class="item" effect="dark" :content="sourceType[`${9}`]" placement="top" v-if="(scope.row.toutiao_openid!=0 && scope.row.toutiao_openid!=''
                     &&scope.row.toutiao_openid!=null && scope.row.toutiao_openid!=undefined&&scope.row.toutiao_openid!='0|0') 
                     ?
                     (scope.row.toutiao_openid!=0 && scope.row.toutiao_openid!=''
                     &&scope.row.toutiao_openid!=null && scope.row.toutiao_openid!=undefined&&scope.row.toutiao_openid!='0|0')
                     :
                     (scope.row.toutiao_openid!=0 && scope.row.toutiao_openid!=''
                     &&scope.row.toutiao_openid!=null && scope.row.toutiao_openid!=undefined&&scope.row.toutiao_openid!='0|0')|| JSON.parse(scope.row.toutiao_openid)!=['0']
                     ">
                        <img height="20" width="20" :src="sourceImg[`${9}`]" alt />
                      </el-tooltip> -->
                             <el-tooltip class="item" effect="dark" :content="sourceType[`${9}`]" placement="top" v-if="scope.row.toutiao_openid!=0 && scope.row.toutiao_openid!=''
                     &&scope.row.toutiao_openid!=null && scope.row.toutiao_openid!=undefined&&scope.row.toutiao_openid!='0|0'&&scope.row.toutiao_openid.length>10">
                        <img height="20" width="20" :src="sourceImg[`${9}`]" alt />
                      </el-tooltip>
                     <el-tooltip class="item" effect="dark" :content="sourceType[`${4}`]" placement="top" v-if="scope.row.wechat_openid!=0 && scope.row.wechat_openid!=''&&scope.row.wechat_openid!=null && scope.row.wechat_openid!=undefined">
                        <img height="20" width="20" :src="sourceImg[`${4}`]" alt />
                      </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="手机号码">
            <!-- <template slot-scope="scope" v-if="scope.row['mobile']"> -->
            <template slot-scope="scope">
              <!-- <span>{{ scope.row.mobile!="" ?scope.row.mobile:未绑定}}</span> -->
                 <span>{{ (scope.row.mobile=="" ||scope.row.mobile==0)  ?'未绑定':scope.row.mobile}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="成交">
            <template slot-scope="scope">
              <p>订单：{{String(scope.row['pay_order']) || '-'}}</p>
              <p>金额：{{scope.row.pay_money || '-'}}</p>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="积分/余额">
            <template slot-scope="scope">
              <div>
                <span>积分：{{scope.row.integral}}</span>
                <router-link style="margin-left:10px" tag="a" target="_blank" :to="{path:'/user/userBalance', query :{ 
                  user_id:scope.row.user_id,classs:1,
                  store_user_id:$route.query.store_user_id?$route.query.store_user_id:'',
                  h_aid:$route.query.h_aid?$route.query.h_aid:'',}}">
                  <el-button type="text">明细</el-button>
                </router-link>
              </div>
              <div>
                <span>余额：{{scope.row.balance}}</span>
                <router-link style="margin-left:10px" tag="a" target="_blank" :to="{path:'/user/userBalance', query :{ 
                  user_id:scope.row.user_id,classs:2,
                  store_user_id:$route.query.store_user_id?$route.query.store_user_id:'',
                  h_aid:$route.query.h_aid?$route.query.h_aid:'',}}">
                  <el-button type="text">明细</el-button>
                </router-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="分销信息">
            <template slot-scope="scope">
              <p>分销商：{{scope.row.is_dealer}}</p>
              <!-- <p>上线：{{scope.row.dealer_name||'-'}}</p> -->
            </template>
          </el-table-column>
          <el-table-column prop="name" label="是否关注公众号">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.have_in_wechat=='1'" type="success">已关注</el-tag>
              <el-tag v-else type="info">未关注</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.remarks" :disabled="!scope.row.isDisabled"  @click.native="activeRemarkInput(scope.row)"  @blur="scope.row.isDisabled=false;saveRemark({user_id:scope.row.user_id,remarks:scope.row.remarks})"></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="name" label="注册时间" >
                    <template slot-scope="scope">
                        <span>{{ scope.row.create_time}}</span>
                    </template>
          </el-table-column>-->
          <!-- <el-table-column prop="name" label="账号状态" >
          <template slot-scope="scope">
            <span>1正常2注销3黑名单</span>
          </template>
          </el-table-column>-->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="operation-group">
                <router-link class="wlm-text" tag="a" target="_blank" :to="{path:'/user/managementUserEdit', query :{ 
                  user_id:scope.row.user_id,is_dealer:scope.row.is_dealer,
                  store_user_id:$route.query.store_user_id?$route.query.store_user_id:'',
                  h_aid:$route.query.h_aid?$route.query.h_aid:'',}}">
                  <el-button type="text">查看</el-button>
                </router-link>
                <!-- <div class="btn-line"></div>
                <el-button
                  class="wlm-text"
                  type="text"
                  @click="changeTableItemToggle(scope.row, {op:scope.row.status === 3 ?'setOutBlackList':'setInBlackList'},tableFormatData.userTable.change.userOp)"
                >{{scope.row.status === 3 ? '移除黑名单':'加入黑名单'}}</el-button> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-content flex-row flex-justify-b flex-align-c">
          <el-row class="pagination-btns">
            <el-checkbox class="check-all" true-label="1" false-label="0" v-model="tableFormatData.userTable.files.checkall" @change="toggleSelection">全部</el-checkbox>
            <!-- <el-button class="right-8" :disabled="isGroup" size="mini" @click="changeTableItem({isGroup:true,op:'setInBlackList'},tableFormatData.userTable.change.userOp)">加入黑名单</el-button> -->
            <!-- <el-button class="right-8" :disabled="isGroup" size="mini" @click="changeTableItem({isGroup:true,op:'setOutBlackList'},tableFormatData.userTable.change.userOp)">移除黑名单</el-button> -->
            <!-- <el-button class="right-8" :disabled="isGroup" size="mini">添加优惠券</el-button> -->
          </el-row>
          <el-pagination
            :disabled="!hasTableData"
            @size-change="listPageChange"
            @current-change="listPageChange"
            :current-page.sync="tableFormatData.userTable.pagination.page"
            :page-sizes="tableFormatData.userTable.pagination.pagesizes"
            :page-size.sync="tableFormatData.userTable.pagination.list_rows"
            layout="total, sizes, prev, pager, next, jumper"
            :total="hasTableData?tableFormatData.userTable.pagination.total : 0"
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  userList,
  userDelete,
  userOp,
  userMerge,
  synWechat,
  userImport,
  getMergeUserInfo,
  synSpeed,
  remarks
} from '@/api/user'
import ExportFileIn from '@/components/ExportFileIn/index'
import mixins from '@/mixins/mixins'
import power from '@/mixins/power'
import exceldown from '@/directive/exceldown'
// import { setTimeout } from 'timers'
export default {
  mixins: [mixins.getters('Table'), power],
  name: 'ManagementUser',
  components: {
    ExportFileIn
  },
  directives: {
    exceldown
  },
  computed: {
    $percentage() {
      let num = (Number(this.nowUpdateFile) / Number(this.allUpdateFile)) * 100
      num = num.toFixed(2)
      if (num > 100) {
        num = 100
      }
      this.$forceUpdate()
      return num
    },
    isIndependent() {
      return this.$store.getters.independent
    }
  },
  data() {
    return {
      state: 0,
      btn: 0,
      // 加载进度
      ProgressBar: 0,
      // 加载是否开启
      visible: false,
      showMask: false,
      nowUpdateFile: 0,
      allUpdateFile: 100,
      getUserMergeData: [],
      exportFileInApi: userImport,
      dialogVisibleImg: false,
      tableFormatData: {
        current: 'userTable',
        userTable: {
          key: 'userTable',
          api: {
            getList: userList,
            delList: userDelete
          },
          tableData: [],
          files: {
            keyword: '',
            remarks: '',
            source: '',
            status: '0',
            time: [],
            ids: [],
            redirect: 'user_id',
            checkall: '0'
          },
          change: {
            userOp: {
              name: '编辑',
              key: 'status',
              api: userOp
            }
          },
          options: {
            status: [{
              lable: '全部',
              value: ''
            }, {
              lable: '正常',
              value: 'normal'
            },
            {
              lable: '禁用',
              value: 'hidden'
            }
            ]
          },
          otherData: {
            is_syn: false
          },
          pagination: {
            page: 1,
            list_rows: 10,
            pagesizes: [10, 20, 50],
            total: 0,
            is_syn: false
          }
        }
      }
    }
  },
  created() {

  },
  methods: {
    filesbtn() {
      console.log('aaaaaaaaa', this.btn)
      this.filesEmpty()
    },
    synchronization() {
      synWechat().then(res => {
        const { data: { msg, code } } = res
        if (code === 1) {
          this.$message.success(msg)
          this.AcquisitionProgress()
        } else {
          this.$message.error(msg)
        }
      })
    },
    setUserMerge(passPindex) {
      this.showMask = true
      const params = {}
      if (passPindex.pindex) {
        params.pindex = passPindex.pindex
        params.max = passPindex.max
        console.log('msg11')
      }
      userMerge(params).then(res => {
        const { data: { msg } } = res
        console.log(msg, 'msg')
        this.nowUpdateFile = msg.now_count
        this.allUpdateFile = msg.total_count
        if (!msg.stop) {
          console.log('msg22')
          this.setUserMerge({ pindex: msg.pindex, max: msg.max })
        } else {
          this.showMask = false
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getUserMerge()
          this.nowUpdateFile = 0
          this.allUpdateFile = 100
        }
      })
    },
    getUserMerge() {
      getMergeUserInfo().then(res => {
        const { data: { data } } = res
        this.getUserMergeData = data
      })
      this.dialogVisibleImg = true
    },
    // 递归加载进度条
    AcquisitionProgress() {
      console.log('this.btn++++++++++++++', this.btn)
      this.$nextTick(res => {
        this.tableFormatData.userTable.pagination.is_syn = true
        let a = ''
        if (this.btn == 1) {
          synSpeed().then(res => {
            if (parseFloat(res.data.data.speed) != 0) {
              this.ProgressBar = parseFloat(res.data.data.speed).toFixed(2)
              console.log('789', parseFloat(res.data.data.speed))
              a = setTimeout(res => {
                this.AcquisitionProgress()
              }, 1500)
            } else if (parseFloat(res.data.data.speed) == 0) {
              this.btn = 0
              clearTimeout(a)
              this.tableFormatData.userTable.pagination.is_syn = false
              return false
            }
          })
        }
      })
    },

    mergeUser() {
      // this.pagination.is_syn = true
      console.log('bb', this.btn)
      this.btn = 1
      synWechat().then(res => {
        const { data: { msg, code } } = res
        if (code === 1) {
          this.$message.success(msg)
          this.AcquisitionProgress()
        } else {
          this.$message.error(msg)
        }
      })
    },
    saveRemark(params) {
      remarks(params).then(res => {
        if (res.data.code == '1') {
          this.$message.success('备注成功')
        } else {
          this.$message.success('备注失败')
        }
      })
    },
    activeRemarkInput(row) {
      this.$set(row, 'isDisabled', true)
    }
  },
  watch: {
    'tableFormatData.userTable.otherData.is_syn': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.btn = 1
          this.AcquisitionProgress()
        }
      }
    }
  },
  destroyed() {
    this.btn = 0
  }

}
</script>

<style lang="scss" scoped>

.remark {
  /deep/ .el-input.is-disabled .el-input__inner {
    cursor: normal !important;
  }
}

// 进度条
.Height {
  height: 34px;
}
.Tips {
  margin-left: 10px;
  margin-right: 10px;
  position: relative;
  z-index: 20;
}
.Tipsbtn{
    position: absolute;
    right: 126px;
    z-index: 10;
}

.management-user {
  .hidemask {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    opacity: 0.9;
    background: #ffffff;
  }

  .yellowBox {
    background: #fff7cc;
    border-radius: 5px;
    padding: 18px 16px;
    margin-bottom: 20px;
  }

  .backBox {
    background: #f8f8f8;
    margin-bottom: 20px;
    padding: 20px;

    .backBoxItem {
      width: 20%;
      text-align: center;
      // padding: 14px 20px;
      box-sizing: border-box;

      .num {
        font-size: 24px;
        font-weight: 600;
      }
    }

    .backBoxItem.B {
      border-left: 1px solid #e2e2e2;
      border-right: 1px solid #e2e2e2;
    }

    .backBoxItem.C {
      border-right: 1px solid #e2e2e2;
    }
  }
}
</style>
